<template>
  <div class="zt-container">
    <div class="iframe-wrapper">
      <iframe
        ref="iframeRef"
        :src="ztAddress"
        class="zt-iframe"
        frameborder="0"
        allowfullscreen
        @error="handleIframeError"
        @load="handleIframeLoad"
      ></iframe>
    </div>

    <div v-if="loading" class="overlay loading">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <span>加载中...</span>
    </div>

    <div v-else-if="error" class="overlay error">
      <el-icon>
        <WarningFilled />
      </el-icon>
      <span>加载失败：{{ error }}</span>
      <el-button @click="loadConfig" type="primary" size="small" style="margin-top: 10px;">
        重试
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Loading, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const loading = ref(true)
const error = ref(null)
const ztAddress = ref('')
const iframeRef = ref(null)

// 读取配置文件
async function loadConfig() {
  loading.value = true
  error.value = null
  
  try {
    // 从 public 目录读取 config.json
    const response = await fetch('/config.json')
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const config = await response.json()
    
    if (!config.ztAddress) {
      throw new Error('配置文件中未找到 ztAddress 字段')
    }
    
    // 获取 token
    const token = getToken()
    
    // 构建完整的 URL，添加 token 参数
    let finalUrl = config.ztAddress
    if (token) {
      // 检查 URL 是否已经包含参数
      const separator = finalUrl.includes('?') ? '&' : '?'
      finalUrl = `${config.ztAddress}${separator}token=${token}`
    }
    
    ztAddress.value = finalUrl
    console.log('读取配置成功，ztAddress:', finalUrl)
    console.log('最终完整 URL:', finalUrl)
    // 配置加载成功后，显示 iframe，loading 由 iframe 的 load 事件控制
    // 如果 iframe 一直不加载，设置超时自动隐藏 loading
    setTimeout(() => {
      if (loading.value) {
        console.warn('iframe 加载超时，强制隐藏 loading')
        loading.value = false
      }
    }, 2000) // 10秒超时
    
  } catch (err) {
    console.error('读取配置文件失败:', err)
    error.value = err.message || '未知错误'
    loading.value = false
    ElMessage.error('加载配置失败：' + err.message)
  }
}

// iframe 加载完成事件
function handleIframeLoad() {
  console.log('iframe 加载完成')
  loading.value = false
  // 检查 iframe 是否可以访问内容
  try {
    const iframe = iframeRef.value
    if (iframe && iframe.contentWindow) {
      console.log('iframe 可以访问 contentWindow')
    } else {
      console.warn('iframe contentWindow 无法访问，可能是跨域问题')
    }
  } catch (e) {
    console.warn('跨域安全限制:', e.message)
  }
}

// iframe 错误处理
function handleIframeError() {
  console.error('iframe 加载失败')
  error.value = 'iframe 加载失败，请检查目标地址是否正确'
  ElMessage.error('iframe 加载失败')
  loading.value = false
}

onMounted(() => {
  loadConfig()
})
</script>

<style lang="scss" scoped>
.zt-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .overlay {
    position: absolute;
    inset: 0;
    z-index: 2;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-size: 16px;
    color: #666;
    
    .el-icon {
      font-size: 48px;
      color: #409eff;
      margin-bottom: 16px;
      
      &.is-loading {
        animation: rotating 2s linear infinite;
      }
    }
    
    span {
      margin-top: 10px;
    }
  }
  
  .error {
    color: #f56c6c;
    
    .el-icon {
      color: #f56c6c;
    }
  }
  
  .iframe-wrapper {
    width: 100%;
    height: 100%;
    overflow: auto;
    .zt-iframe {
      width: 100%;
      height: 100%;
      border: none;
      display: block;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>